#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
    //QByteArray data = "\xC4\xFA\xD2\xD1\xBE\xAD\xB3\xC9\xB9\xA6\xB5\xC7\xC2\xBC\xA1\xA3";
    //qDebug()<<QTextCodec::codecForName("GBK")->toUnicode(data);
    QFile file(GetSaveFile());
    file.open(QIODevice::ReadOnly);
    QDataStream ds(&file);
    Load(ds);
    file.close();
    ui->tabWidget->setCurrentIndex(0);
    if(ui->checkBox_2->isChecked())emit on_pushButton_clicked();
}

Widget::~Widget()
{
    QFile file(GetSaveFile());
    file.open(QIODevice::WriteOnly);
    QDataStream ds(&file);
    Save(ds);
    file.close();
    delete ui;
}

void Widget::requestFinished(QNetworkReply *reply)
{
    qDebug()<<reply->url();

    QVariant statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
    if(statusCode.isValid())
        qDebug() << "status code=" << statusCode.toInt();

    QVariant reason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
    if(reason.isValid())
        qDebug() << "reason=" << reason.toString();

    QNetworkReply::NetworkError err = reply->error();
    if(err != QNetworkReply::NoError)
        qDebug() << "Failed: " << reply->errorString();
    else {
        if(reply->url().url().indexOf("10.211.220.9/0.htm") != -1){
            QByteArray ret = reply->readAll();
            QString tmp = AutoDecode(ret);
            //<title>登录成功</title>
            tmp = GetSubString(tmp,"<title>(.*)</title>");
            if(tmp == "信息返回")tmp = "登录失败";
            ui->label->setText(tmp);
        }else if(reply->url().url().indexOf("210.45.147.188:8080/reader/redr_verify.php") != -1){
            QString ret = reply->readAll();
            if(first){
                first = false;
                csrf = GetSubString(ret,"name=\"csrf_token\" value=\"(.*)\" />");
                qDebug()<<csrf;
                SendRequest("http://210.45.147.188:8080/reader/captcha.php");
            }else {
                if(statusCode.toInt() == 302){
                    SendRequest("http://210.45.147.188:8080/reader/redr_info.php");
                }else{
                    ui->label_3->setText(GetSubString(ret,"color=\"red\">(.*)</font>"));
                }
            }
        }else if(reply->url().url().indexOf("210.45.147.188:8080/reader/captcha.php") != -1){
            QPixmap img;
            img.loadFromData(reply->readAll());
            ui->label_2->setPixmap(img);
        }else if(reply->url().url().indexOf("210.45.147.188:8080/reader/redr_info.php") != -1){
            QString ret = reply->readAll();
            name = GetSubString(ret,"<span class=\"profile-name\">(.*)</span> </div>\r\n");
            ui->label_3->setText(name);
            SendRequest("http://210.45.147.188:8080/reader/book_lst.php");
        }else if(reply->url().url().indexOf("210.45.147.188:8080/reader/book_lst.php") != -1){
            QString ret = reply->readAll();
            QStringList id = GetSubStringEX(ret,"<td class=\"whitetext\" width=\"10%\">(.*)</td>");
            QStringList time = GetSubStringEX(ret,"<td class=\"whitetext\" width=\"13%\">(.*)</td>");
            QStringList book = GetSubStringEX(ret,"marc_no=(.*)</td>");
            books.clear();
            for (int i=0;i<id.length();++i) {
                Book tmp;
                tmp.id = id[i];
                tmp.time_begin = time[i*2];
                tmp.time_end = time[2*i+1];
                tmp.time_end.replace("<font color=>","").replace("        </font>","");
                QStringList data = book[i].split("\">");
                tmp.url = data[0];
                data = data[1].split("</a> / ");
                tmp.name = Unescape(data[0]);
                tmp.author = Unescape(data[1]);
                books.append(tmp);
                qDebug()<<tmp.id<<tmp.time_begin<<tmp.time_end<<tmp.name<<tmp.author<<tmp.url;
            }
            RefreshBooksDisplay();
        }else{
            qDebug()<<reply->readAll();
        }
    }
}

QString Widget::GetSubString(QString src, QString pattern)
{
    return GetSubStringEX(src,pattern)[0];
}

QStringList Widget::GetSubStringEX(QString src, QString pattern)
{
    QStringList ret;
    QRegExp rx(pattern);
    rx.setMinimal(true);
    int pos = 0;
    while((pos = rx.indexIn(src,pos)) != -1){
        ret<<rx.capturedTexts()[1];
        pos+=rx.matchedLength();
    }
    return ret;
}

QString Widget::Unescape(QString src)
{
    QTextDocument doc;
    doc.setHtml(src);
    return doc.toPlainText();
}

QString Widget::MD5(QByteArray data)
{
    return QCryptographicHash::hash(data,QCryptographicHash::Md5).toHex();
}

void Widget::SendRequest(QString url, QString data)
{
    QNetworkRequest req((QUrl(url)));
    if(data!=""){
        req.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/x-www-form-urlencoded"));
        manager->post(req,data.toUtf8());
    }else{
        manager->get(req);
    }
}

QString Widget::AutoDecode(QByteArray data)
{
    QTextCodec::ConverterState state;
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");
    QString text = codec->toUnicode(data.constData(), data.size(), &state);
    if (state.invalidChars > 0)text = QTextCodec::codecForName("GBK")->toUnicode(data);
    return text;
}

QString Widget::GetSaveFile()
{
    /*
        QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        QFile assets_path("assets:/" + assetFileName);
        assets_path.copy(path + "/" + assetFileName);
        QFile::setPermissions(path + "/" + assetFileName, QFileDevice::ReadUser | QFileDevice::WriteUser);
        return path + "/" + assetFileName;
    */
    QString filename = "AustHelper.bin";
    QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
    QDir dir(path);
    if(!dir.exists())dir.mkpath(path);
    QFile::setPermissions(path + "/" + filename, QFileDevice::ReadUser | QFileDevice::WriteUser);
    qDebug()<<path + "/" + filename;
    return path + "/" + filename;
}

void Widget::Save(QDataStream &ds)
{
    ds<<ui->lineEdit->text()<<ui->lineEdit_2->text()<<ui->checkBox->isChecked()<<ui->checkBox_2->isChecked()<<ui->lineEdit_5->text()<<ui->lineEdit_3->text();
}

void Widget::Load(QDataStream &ds)
{
    QString tmp;
    bool tmp2;
    ds>>tmp;
    ui->lineEdit->setText(tmp);
    ds>>tmp;
    ui->lineEdit_2->setText(tmp);
    ds>>tmp2;
    ui->checkBox->setChecked(tmp2);
    ds>>tmp2;
    ui->checkBox_2->setChecked(tmp2);
    ds>>tmp;
    ui->lineEdit_5->setText(tmp);
    ds>>tmp;
    ui->lineEdit_3->setText(tmp);
}

void Widget::RefreshBooksDisplay()
{
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
    ui->tableWidget->horizontalHeader()->autoScrollMargin();
    ui->tableWidget->setRowCount(books.length());
    for(int i=0;i<books.length();++i){
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(books[i].id));
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(books[i].name));
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(books[i].author));
        ui->tableWidget->setItem(i,3,new QTableWidgetItem(books[i].time_begin));
        ui->tableWidget->setItem(i,4,new QTableWidgetItem(books[i].time_end));
        ui->tableWidget->setItem(i,5,new QTableWidgetItem(books[i].url));
    }
}

void Widget::on_pushButton_clicked()
{
    if(ui->lineEdit->text()=="" || ui->lineEdit_2->text()==""){
        ui->label->setText("请输入用户名和密码！");return;
    }
    QString url = "http://10.211.220.9/0.htm";
    QString data = "DDDDD="+ui->lineEdit->text();
    data += ui->radioButton_2->isChecked()?"%40aust":"";
    data += "&upass="+MD5(QString("2"+ui->lineEdit_2->text().toLatin1()+"12345678").toUtf8());
    data += "123456782";
    data += "&R1=0&R2=";
    data += ui->radioButton_2->isChecked()?"1":"0";
    data += "&para=00&0MKKey=123456&v6ip=";
    SendRequest(url,data);
}

void Widget::on_pushButton_2_clicked()
{
    SendRequest("http://10.211.220.9/F.htm");
    ui->label->setText("注销成功");
}

void Widget::on_checkBox_2_stateChanged(int arg1)
{
    if(ui->checkBox_2->isChecked()==true)ui->checkBox->setChecked(true);
}

void Widget::on_pushButton_3_clicked()
{
    QString data="number="+ui->lineEdit_5->text()+"&passwd="+ui->lineEdit_3->text()+"&captcha="+ui->lineEdit_4->text()+"&select=cert_no&returnUrl=&csrf_token="+csrf;
    SendRequest("http://210.45.147.188:8080/reader/redr_verify.php",data);
}

void Widget::on_pushButton_4_clicked()
{
    SendRequest("http://210.45.147.188:8080/reader/captcha.php");
}

void Widget::on_tabWidget_currentChanged(int index)
{
    if(index == 1){
        static bool hasInit = false;
        if(!hasInit){
            hasInit = true;
            SendRequest("http://210.45.147.188:8080/reader/redr_verify.php");
        }
    }
}
